#import "CompassModule.h"

@implementation CompassModule
{
  CLLocationManager *locationManager;
  BOOL hasListeners;
}

RCT_EXPORT_MODULE();

+ (BOOL)requiresMainQueueSetup
{
  return YES;
}

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"headingUpdated"];
}

// 启动罗盘监听
RCT_EXPORT_METHOD(startHeadingUpdates)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    if (self->locationManager == nil) {
      self->locationManager = [[CLLocationManager alloc] init];
      self->locationManager.delegate = self;
    }
    
    if ([CLLocationManager headingAvailable]) {
      [self->locationManager startUpdatingHeading];
      NSLog(@"[CompassModule] 开始监听罗盘方向");
    } else {
      NSLog(@"[CompassModule] 设备不支持罗盘");
    }
  });
}

// 停止罗盘监听
RCT_EXPORT_METHOD(stopHeadingUpdates)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    if (self->locationManager != nil) {
      [self->locationManager stopUpdatingHeading];
      NSLog(@"[CompassModule] 停止监听罗盘方向");
    }
  });
}

// 检查罗盘是否可用
RCT_EXPORT_METHOD(isHeadingAvailable:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  BOOL available = [CLLocationManager headingAvailable];
  resolve(@(available));
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
  if (hasListeners) {
    // magneticHeading: 磁北方向 (0-359度)
    // trueHeading: 真北方向 (需要位置权限)
    // headingAccuracy: 精度 (负值表示无效)
    
    double heading = newHeading.magneticHeading;
    if (heading < 0) {
      heading = 0;
    }
    
    [self sendEventWithName:@"headingUpdated" body:@{
      @"heading": @(heading),
      @"accuracy": @(newHeading.headingAccuracy)
    }];
  }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
  NSLog(@"[CompassModule] 罗盘错误: %@", error.localizedDescription);
}

#pragma mark - RCTEventEmitter

- (void)startObserving
{
  hasListeners = YES;
}

- (void)stopObserving
{
  hasListeners = NO;
}

@end
